﻿/**

 @Name: 中恒业主入口

 */
 

layui.define(['layer', 'laytpl', 'form', 'element', 'upload', 'util','table'], function(exports){
  
  var $ = layui.jquery
  ,layer = layui.layer
  ,laytpl = layui.laytpl
  ,form = layui.form
  ,table = layui.table
  ,element = layui.element
  ,upload = layui.upload
  ,util = layui.util
  ,device = layui.device()

  ,DISABLED = 'layui-btn-disabled';

  var layer_copy_index;
  
  //阻止IE7以下访问
  if(device.ie && device.ie < 8){
    layer.alert('如果您非得使用 IE 浏览器访问中恒业，那么请使用 IE8+');
  }

  $.ajaxSetup({
    headers: {
      'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
    },
    beforeSend:function(xhr,obj){
      if(obj.global){
        layer.load();
      }
    },
    error:function(xhr){
      if (xhr.status === 401) {
        layer.msg('请先登录',{time:1000},function() {
          location.href = '/login';
        });
      }
    },
    complete:function(obj){
      layer.closeAll('loading');
    }
  });
  
  layui.focusInsert = function(obj, str){
    var result, val = obj.value;
    obj.focus();
    if(document.selection){ //ie
      result = document.selection.createRange(); 
      document.selection.empty(); 
      result.text = str; 
    } else {
      result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
      obj.focus();
      obj.value = result.join('');
    }
  };


  //数字前置补零
  layui.laytpl.digit = function(num, length, end){
    var str = '';
    num = String(num);
    length = length || 2;
    for(var i = num.length; i < length; i++){
      str += '0';
    }
    return num < Math.pow(10, length) ? str + (num|0) : num;
  };
  
  var ztk = {
    json: function(url, data, success, options){
      var that = this, type = typeof data === 'function';
      
      if(type){
        options = success;
        success = data;
        data = {};
      }

      options = options || {};

      return $.ajax({
        type: options.type || 'post',
        dataType: options.dataType || 'json',
        data: data,
        url: url,
        success: function(res){
          if(res.code === 0) {
            success && success(res);
          } else {
            layer.msg(res.msg || res.code, {shift: 6});
            options.error && options.error();
          }
        }, error: function(e){
          layer.msg('请求异常，请重试', {shift: 6});
          options.error && options.error(e);
        }
      });
    }
    ,charLen: function(val){
      var arr = val.split(''), len = 0;
      for(var i = 0; i <  val.length ; i++){
        arr[i].charCodeAt(0) < 299 ? len++ : len += 2;
      }
      return len;
    }
    
    ,form: {}
    ,viewTaskCopy: function (data) {
      layer_copy_index = layer.open({
        type: 1,
        shadeClose: true,
        content: $('#view-copy'),
        title : '查看文案',
        area: ['600px', '600px'],
        success: function(layero, index){
          $('#view-copy .copy-image').attr('src',data.market_image.replace('https:',''));
          $('#view-copy .copy-content').html(data.content.replace(/\n/g,'<br/>'));
        }
      });
    }
    ,jiedan : function (data) {
      if(data.status != 1){
        return false;
      }
      layer.confirm('确定要接受该任务吗？', {
        btn : [ '确定', '取消' ]//按钮
      }, function(index) {
        $.post("/order-taking",{task_id:data.id},function(obj){
          if(obj.code === 0){
            layer.msg(obj.msg,{icon:1,time:1000},function() {
              location.reload();
            });
          }else{
            layer.msg(obj.msg);
          }
        },'JSON');
      });
    }
    ,taskOrderDetail: function (data) {
      layer.open({
        type: 1,
        shadeClose: true,
        content: $('#order-list-div'),
        title : '任务详情',
        area: ['700px', '600px'],
        success: function(layero, index){
          table.render({
            elem: '#table-list-order'
            ,url: '/order-receiveDetail'
            ,cols: [[
              {field:'union_name', title: '接单人'}
              ,{field:'created_at', title: '接单时间'}
              ,{field:'finish_at',  title: '完成时间'}
              ,{field:'status_name', title: '状态',templet:function(d){
                  return '<span class="layui-badge '+d.status_color+'">'+d.status_name+'</span>';
                }}
              ,{field:'taokeyi_at',  title: '淘客易收录'}
            ]]
            ,where: {
              user_id: data.user_id,
              task_id: data.id
            }
            ,page: {
              layout: ['prev', 'page', 'next']
            }

          });

          $('#order-list-div .receive_num').text(data.receive_num);
          $('#order-list-div .finish_num').text(data.finish_num);
          $('#order-list-div .no_finish_num').text(data.receive_num - data.finish_num);
          $('#order-list-div .taokeyi2 a').attr('href','https://www.tkeasy.com/item/'+data.goods_id);
          $('#order-list-div .taokeyi2 iframe').attr('src','https://www.tkeasy.com/item/'+data.goods_id);
        }
      });
    }
    ,agreeOrder : function (data) {
      $.post("/order-agreeOrRefuse",{order_id:data.id,type:1},function(obj){
        if(obj.code === 0){
          layer.msg(obj.msg,{icon:1,time:1000},function() {
            location.reload();
          });
        }else{
          layer.msg(obj.msg);
        }
      },'JSON');
    }
    ,refuseOrder : function (data) {
      layer.confirm('确定要同意吗？', {
        btn : [ '确定', '取消' ]//按钮
      }, function(index) {
        $.post("/order-agreeOrRefuse",{order_id:data.id,type:2},function(obj){
          if(obj.code === 0){
            layer.msg(obj.msg,{icon:1,time:1000},function() {
              location.reload();
            });
          }else{
            layer.msg(obj.msg);
          }
        },'JSON');
      });
    },xiajia : function (data) {
          $.post("/task-status",{task_id:data.id},function(obj){
              if(obj.code === 0){
                  layer.msg(obj.msg,{icon:1,time:1000},function() {
                      location.reload();
                  });
              }else{
                  layer.msg(obj.msg);
              }
          },'JSON');
    },sucai : function (data) {
      console.log(data);
      var getTpl = $('#sucaiInfo').html();
      laytpl(getTpl).render(data, function(html){
        getTpl = html;
      });
      layer.open({
        type: 1
        ,title :'素材信息'
        ,area: ['1000px', '100%']
        // ,anim: 5
        ,shadeClose: true
        ,offset: 'rb' //具体配置参考：offset参数项
        ,content: getTpl
        ,shade: [0.8, 'rgba(0,0,0,.5)']
        ,success: function(){
            
        }
      });
    },shequnxiajia : function (data) {
          $.post("/shequn-status",{id:data.id,isDelete:1},function(obj){
              if(obj.code === 0){
                  layer.msg(obj.msg,{icon:1,time:1000},function() {
                      location.reload();
                  });
              }else{
                  layer.msg(obj.msg);
              }
          },'JSON');
      }
    ,
  };

  if($(window).width() > 750){
    layer.photos({
      photos: '.photos'
      ,zIndex: 9999999999
      ,anim: -1
    });
  } else {
    $('body').on('click', '.photos img', function(){
      window.open(this.src);
    });
  }

  form.on('submit(*)', function(data){
    var action = $(data.form).attr('action'), button = $(data.elem);
    ztk.json(action, data.field, function(res){
      var end = function(){
        if(res.data.action){
          layer.msg(res.msg,{icon:1,time:1000},function() {
            location.href = res.data.action;
          });
        } else {
          // ztk.form[action||button.attr('key')](data.field, data.form);
          layer.msg(res.msg,{icon:1,time:1000});
        }
      };
      if(res.code === 0){
        button.attr('alert') ? layer.alert(res.msg, {
          icon: 1,
          time: 10*1000,
          end: end
        }) : end();
      }
    });
    return false;
  });

  table.on('tool(table-list)', function(obj){
    var data = obj.data;
    if(obj.event === 'taskOrderDetail'){
      ztk.taskOrderDetail(data);
    } else if(obj.event === 'viewTaskCopy'){
      ztk.viewTaskCopy(data);
    } else if(obj.event === 'jiedan'){
      ztk.jiedan(data);
    }else if(obj.event === 'agreeOrder'){
      ztk.agreeOrder(data);
    }else if(obj.event === 'refuseOrder'){
      ztk.refuseOrder(data);
    }else if(obj.event === 'xiajia'){
        ztk.xiajia(data);
    }else if(obj.event === 'sucai'){
      ztk.sucai(data);
    }else if(obj.event === 'shequnxiajia'){
        ztk.shequnxiajia(data);
    }
  });


  $(document).on('click','.copy-btn',function(obj){

    var clipboard = new ClipboardJS('.copy-btn', {
      target:function(){
        return document.querySelector('.copy-text-image');
      }
    });

    clipboard.on('success', function(e) {
      e.clearSelection();
      layer.msg('复制成功');
      console.log(e);
    });

    clipboard.on('error', function(e) {
      layer.msg('复制失败,您可以选择手动复制');
      console.log(e);
    });

    this.click();  //解决clipboard二次点击生效问题
    clipboard.destroy();

    layer.close(layer_copy_index);
  });

  $('.search-btn').on('click',function(){
    var keywords = $('#keywords').val();
    table.reload('table-list', {
      where: {
        keywords: keywords
      }
      , page: {
        curr: 1
      }
    });
  });

  //加载特定模块
  if(layui.cache.page && layui.cache.page !== 'index'){
    var extend = {};
    extend[layui.cache.page] = layui.cache.page;
    layui.extend(extend);
    layui.use(layui.cache.page);
  }

  //手机设备的简单适配
  var treeMobile = $('.site-tree-mobile')
  ,shadeMobile = $('.site-mobile-shade');

  treeMobile.on('click', function(){
    $('body').addClass('site-mobile');
  });

  shadeMobile.on('click', function(){
    $('body').removeClass('site-mobile');
  });
  
  //固定Bar
  util.fixbar({
    bar1: '&#xe642;'
    ,bgcolor: '#009688'
    ,click: function(type){
      if(type === 'bar1'){
        //layer.msg('打开 index.js，开启发表新帖的路径');
        location.href = '/task-add';
      }
    }
  });
  exports('ztk', ztk);
});

